package com.yao.system.aspect;


import cn.hutool.json.JSONUtil;
import com.yao.system.annotation.MyAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

@Component
@Aspect
@Slf4j
public class MyAspect {
    @Pointcut("@annotation(com.yao.system.annotation.MyAnnotation)")
    public void pointcut(){}

    @Before("pointcut()")
    public void beforeLog(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature= (MethodSignature) signature;
        Method method1 = methodSignature.getMethod();
        Annotation[] annotations = method1.getAnnotations();
        Type returnType = method1.getGenericReturnType();
        String methodName = signature.getName();

        log.info("==============================开始执行 接口名：{} ====================",methodName);
        StringBuffer url = request.getRequestURL();
        log.info("======请求URL : {}",url);
        String method = request.getMethod();
        log.info("===========请求方法:{}",method);
        log.info("=======全路径及执行方法:{},{}",signature.getDeclaringTypeName(),methodName);
        log.info("========  IP   : {}",request.getRemoteHost());
        log.info("===== 请求入参:{}", JSONUtil.toJsonStr(joinPoint.getArgs()));
        log.info("============================================================");

    }

    @After("pointcut()")
    public void afterLog(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Signature signature = joinPoint.getSignature();
        String methodName = signature.getName();

        log.info("============================== 接口：{} 执行完成 ====================",methodName);

    }


    //@Around("@annotation(annotation)")
    //public Object tiem(ProceedingJoinPoint joinPoint,MyAnnotation annotation) throws Throwable {
    //    ServletRequestAttributes requestAttributes =
    //            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    //    return joinPoint.proceed();
    //}

}
